<template>
  <view class="page page-primary page-coupon-list has-fixed-footer">
    <page-header theme="colorful"></page-header>
    <view class="page-content">
      <view class="page-statistic">
        <view class="statistic-header-name"><fui-text text="支付金额(元)" size="28" color="#666"></fui-text></view>
        <view class="statistic-header-value"><fui-text :text="utils.moneyFormatter(statisticData.paymentAmount)" size="56" color="var(--fui-color-primary)" fontWeight="bold"></fui-text></view>
        <view class="statistic-content-list">
          <view class="statistic-content-item">
            <view class="statistic-item-name"><fui-text text="发放张数(张)" size="24" color="#999"></fui-text></view>
            <view class="statistic-item-value"><fui-text :text="statisticData.grantNumber" size="36" color="#666" fontWeight="bold"></fui-text></view>
          </view>
          <view class="statistic-content-item">
            <view class="statistic-item-name"><fui-text text="使用张数(张)" size="24" color="#999"></fui-text></view>
            <view class="statistic-item-value"><fui-text :text="statisticData.useNumber" size="36" color="#666" fontWeight="bold"></fui-text></view>
          </view>
          <view class="statistic-content-item">
            <view class="statistic-item-name"><fui-text text="支付采购方数" size="24" color="#999"></fui-text></view>
            <view class="statistic-item-value"><fui-text :text="statisticData.buyerNumber" size="36" color="#666" fontWeight="bold"></fui-text></view>
          </view>
        </view>
      </view>
      <view class="page-tab">
        <fui-tabs :tabs="tabs" @change="handleChangeTab" background="rgba(0,0,0,0)" size="32" color='#666666' sliderRadius=-1 :center='true' fontWeight='bold' selectedSize='32' selectedColor='var(--fui-color-primary)' scale='1' sliderHeight='8' selectedFontWeight='bold' bottom=3></fui-tabs>
      </view>
			<view class="coupon-list">
				<view class="coupon-item" v-for="item in listData" :key="item.id">
          <fui-bubble-box v-if="item.status == 11" :ref="`couponMenu${item.id}`" :isMask="false" direction="bottom" position="absolute" right="40" width="128" :show="item.showMenu" :triangle="{ left: 100 }" @close="item.showMenu = false">
            <fui-icon name="more-fill" size="42" color="#999" @click="handleShowMenu(item)"></fui-icon>
            <template #content>
              <view class="bubble-item" @click="handlePublish(item)"><image class="bubble-item-icon" src="/static/images/coupon/icon-publish.png"></image><fui-text text="发布" size="24" color="var(--fui-color-primary)"></fui-text></view>
              <view class="bubble-item" @click="handleDelete(item)"><image class="bubble-item-icon" src="/static/images/coupon/icon-delete.png"></image><fui-text text="删除" size="24" color="var(--fui-color-danger)"></fui-text></view>
            </template>
          </fui-bubble-box>
          <view @click="handleToView(item)">
            <view class="coupon-item-name">
              <fui-text :text="item.name" size="28" color="#333" fontWeight="bold"></fui-text>
            </view>
            <view class="coupon-item-type">{{ COUPON_USER_TYPE[item.targetCrowd].name }} — {{ COUPON_GOODS_RANGE[item.productScope].name }}</view>
            <view class="coupon-item-statistic">
              <view class="coupon-statistic-item">
                <view class="coupon-statistic-value">
                  <fui-text text="满" size="32" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                  <fui-text :text="item.discountRules.split('-')[0]" size="32" :padding="[0, '8rpx']" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                  <fui-text text="减" size="32" :padding="[0, '8rpx']" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                  <fui-text :text="item.discountRules.split('-')[1]" size="32" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                </view>
                <view class="coupon-statistic-name"><fui-text text="满减门槛及金额" size="24" color="var(--fui-color-primary)"></fui-text></view>
              </view>
              <view class="coupon-statistic-item">
                <view class="coupon-statistic-value">
                  <fui-text :text="formatValue(item.grantNumber || 0)" size="32" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                  <fui-text :text="formatUnit(item.grantNumber || 0, '张')" size="32" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                  <fui-text text="/" size="32" :padding="[0, '8rpx']" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                  <fui-text :text="formatValue(item.issueNumber || 0)" size="24" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                  <fui-text :text="formatUnit(item.issueNumber || 0, '张')" size="24" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
                </view>
                <view class="coupon-statistic-name"><fui-text text="发行及领取进度" size="24" color="var(--fui-color-primary)"></fui-text></view>
              </view>
            </view>
            <view class="coupon-item-text">
              <fui-text text="可领取时间：" size="24" color="#999"></fui-text>
              <fui-text :text="utils.dateFormatter(item.receiveStartTime, 'y-m-d h:i', 2, true)" size="24" color="#999"></fui-text>
              <fui-text text="-" :padding="[0, '16rpx']" size="24" color="#999"></fui-text>
              <fui-text :text="utils.dateFormatter(item.receiveEndTime, 'y-m-d h:i', 2, true)" size="24" color="#999"></fui-text>
            </view>
            <view class="coupon-item-text">
              <fui-text text="可使用时间：" size="24" color="#999"></fui-text>
              <fui-text :text="utils.dateFormatter(item.useStartTime, 'y-m-d h:i', 2, true)" size="24" color="#999"></fui-text>
              <fui-text text="-" :padding="[0, '16rpx']" size="24" color="#999"></fui-text>
              <fui-text :text="utils.dateFormatter(item.useEndTime, 'y-m-d h:i', 2, true)" size="24" color="#999"></fui-text>
            </view>
          </view>
				</view>
			</view>
      <fui-loadmore :state="moreState"></fui-loadmore>
      <view class="ui-fixed-footer">
        <fui-button text="新增优惠券" height="78rpx" @click="handleToAdd"></fui-button>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, inject } from 'vue'
import { onShow, onPullDownRefresh, onReachBottom } from "@dcloudio/uni-app"
import { useStore } from 'vuex'
import { COUPON_STATUS, COUPON_USER_TYPE, COUPON_GOODS_RANGE } from './consts'
import { formatValue, formatUnit } from '@/utils/tools'
import utils from '@/components/firstui/fui-utils'
import pageHeader from '@/components/header'
import couponApi from '@/api/coupon'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

onShow(() => {
  getStatisticsData()
  getCouponList()
})

// 标签页
const tabs = ref(Object.values(COUPON_STATUS))
const handleChangeTab = (e) => {
  queryParams.value.pageNo = 1
  queryParams.value.status = e.code
  getCouponList()
}

// 下拉菜单
const handleShowMenu = (row) => {
  listData.value.forEach(item => {
    item.showMenu = item.id === row.id
  })
}

// 发布
const handlePublish = (row) => {
  row.showMenu = false
  modal.confirm(`确认发布优惠券"${row.name}"？`).then(() => {
    couponApi.updateCouponStatus({
      id: row.id,
      status: 12
    }).then((res) => {
      if (res.code === 0) {
        modal.msg(`【${row.name}】已发布！`)
        getCouponList()
      } else {
        modal.msgError(res.msg || `【${row.name}】发布失败！`)
      }
    }).catch(err => {
      modal.msgError(err.msg || err || `【${row.name}】发布失败！`)
    })
  })
}

// 删除
const handleDelete = (row) => {
  row.showMenu = false
  modal.confirm(`确认删除优惠券"${row.name}"？`).then(() => {
    couponApi.deleteCoupon(row.id).then((res) => {
      if (res.code === 0) {
        modal.msg(`【${row.name}】已删除！`)
        getCouponList()
      } else {
        modal.msgError(res.msg || `【${row.name}】删除失败！`)
      }
    }).catch(err => {
      modal.msgError(err.msg || err || `【${row.name}】删除失败！`)
    })
  })
}

// 获取活动列表
const moreState = ref(1)
const listData = ref([])
const queryParams = ref({
  pageNo: 1,
  pageSize: 10,
  status: '11',
  name: ''
})
const getCouponList = (() => {
  uni.stopPullDownRefresh()
  try {
    if (store.getters.userType != 1) {
      queryParams.value.supplierId = store.getters.companyId
    }
    modal.loading('加载中...')
    couponApi.getCouponList(queryParams.value).then((res) => {
      modal.closeLoading()
      if (res.code == 0) {
        const newData = res.data && res.data.list ? res.data.list : []
        newData.forEach(item => {
          item.showMenu = false
        })
        if (queryParams.value.pageNo * queryParams.value.pageSize >= res.data.total) {
          moreState.value = 3
        } else {
          moreState.value = 1
        }
        if (queryParams.value.pageNo > 1) {
          listData.value = [...listData.value, ...newData]
        } else {
          listData.value = [...newData]
        }
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch(err) {
    modal.closeLoading()
  }
})

// 获取统计数据
const statisticData = ref({})
const getStatisticsData = () => {
  try {
    couponApi.getStatisticData({
      couponType: store.getters.userType == 1 ? 51 : 52,
      queryType: 41,
      period: 0,
      id: store.getters.userType == 1 ? '' : store.getters.companyId
    }).then(res => {
      if (res.code === 0 && res.data) {
        statisticData.value = res.data || {}
      } else {
        modal.msgError('获取统计数据失败！')
      }
    })
  } catch(err) {
    modal.msgError('获取统计数据失败！')
  }
}

// 新增活动
const handleToAdd = () => {
  tab.navigateTo('/pages/coupon/form')
}

// 跳转活动详情
const handleToView = (coupon) => {
  if (coupon.status == 11) {
    tab.navigateTo(`/pages/coupon/form?couponId=${coupon.id}`)
  } else {
    tab.navigateTo(`/pages/coupon/view?couponId=${coupon.id}`)
  }
}

// 下拉刷新
onPullDownRefresh(() => {
  queryParams.value.pageNo = 1
  getCouponList()
})

// 上拉加载更多
onReachBottom(() => {
  if (moreState.value == 1) {
    modal.loading('加载中...')
    moreState.value = 2
    queryParams.value.pageNo++
    getCouponList()
  }
})
</script>

<style lang="scss" scoped>
.page-coupon-list {
  .page-statistic {
    width: 100%;
    background: #ffffff;
    padding: 36rpx;
    box-sizing: border-box;
    border-radius: 16rpx;
    .statistic-header-value {
      margin-bottom: 28rpx;
      text-align: center;
    }
    .statistic-content-list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .statistic-content-item {
        text-align: center;
        .statistic-item-name {
          margin-bottom: 8rpx;
        }
      }
    }
  }
  .page-tab {
    position: relative;
    margin-top: 30rpx;
    .ui-btn-primary_plain {
      position: absolute;
      top: 30rpx;
      right: 0;
      ::v-deep .fui-button {
        background-color: #ecf4ff !important;
        font-weight: bold;
      }
    }
    :deep(.fui-tabs__scrollbox) {
      width: fit-content;
    }

    :deep(.fui-tabs__line-short) {
      width: 64rpx !important;
    }

    :deep(.fui-tabs__item) {
      padding-left: 5rpx;
      padding-right: 72rpx;
    }
  }
  .coupon-list {
    .coupon-item {
      position: relative;
      background-color: #fff;
      border-radius: 16rpx;
      margin-top: 24rpx;
      padding: 24rpx;
      ::v-deep .fui-bubble__box-wrap {
        position: absolute;
        top: 24rpx;
        right: 24rpx;
        .fui-bubble__box-triangle {
          box-shadow: 0rpx 0rpx 8rpx 2rpx rgba(0,0,0,0.08);
        }
        .fui-bubble__box-list {
          box-shadow: 0rpx 0rpx 8rpx 2rpx rgba(0,0,0,0.08);
          box-sizing: border-box;
          padding: 0 24rpx;
          .bubble-item {
            display: flex;
            justify-content: center;
            align-items: center;
            padding: 24rpx 0;
            &:not(:last-child) {
              border-bottom: 2rpx solid #E4E4E4;
            }
            .bubble-item-icon {
              width: 20rpx;
              height: 20rpx;
              margin-right: 8rpx;
            }
          }
        }
      }
      .coupon-item-name {
        margin-bottom: 14rpx;
      }
      .coupon-item-type {
        display: inline-block;
        background-color: #F6F6F6;
        border-radius: 4rpx;
        padding: 6rpx 10rpx;
        font-size: 24rpx;
        color: #999;
      }
      .coupon-item-statistic {
        display: flex;
        justify-content: space-between;
        align-items: center;
        background-color: #ECF4FF;
        border-radius: 16rpx;
        margin: 24rpx 0;
        padding: 30rpx;
        .coupon-statistic-item {
          flex: 0 0 50%;
          width: 50%;
          text-align: center;
          &:not(:last-child) {
            position: relative;
            &:after {
              position: absolute;
              top: 50%;
              right: -1rpx;
              content: '';
              width: 2rpx;
              height: 32rpx;
              background-color: #B5C8F9;
              margin-top: -16rpx;
            }
          }
          .coupon-statistic-name {
            margin-top: 10rpx;
          }
        }
      }
      .coupon-item-text {
        margin-bottom: 6rpx;
      }
    }
  }
}
</style>